package cn.kgc.controller;


import cn.kgc.pojo.User;
import cn.kgc.service.UserService;
import cn.kgc.service.UserServiceImpl;
import cn.kgc.util.Contants;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class UserServlet extends HttpServlet {

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }


    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.设置编码格式
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        UserService userService =new UserServiceImpl();

        //2.判断请求是否是登录请求
        String type=req.getParameter("type");
        if(type==null){

            //登录请求
        }else if(Integer.parseInt(type)==1){
            //3.执行登录业务
            String username=  req.getParameter("username");
            String password=  req.getParameter("password");
            User user= userService.login(username,password);
            if(user!=null){
                //4.登录成功，则user放入session
                HttpSession session= req.getSession();
                System.out.println(user.toString());
                session.setAttribute(Contants.LOGIN_USER,user);
                //5.转发新闻主页
                req.getRequestDispatcher("news?type=list").forward(req,resp);

            }
            //登录失败
            req.setAttribute("error","用户名和密码有误，请查验！");
            req.getRequestDispatcher("day04/login.jsp").forward(req,resp);


        }else if(Integer.parseInt(type)==2){
            //注销
           req.getSession().invalidate();
         //   req.getSession().removeAttribute(Contants.LOGIN_USER);
        }


    }
}
